from sqlalchemy import Column, String, DateTime, func
from sqlalchemy.orm import declarative_base
from ..core.database import Base

class Transaction(Base):
    __tablename__ = "transactions"

    id = Column(String, primary_key=True)
    trans_code = Column(String(3), nullable=False)  # 交易类型
    trans_sn = Column(String(30), nullable=False)   # 交易流水号
    rrn = Column(String(12))                        # 参考号
    orderid = Column(String(30))                    # 订单号
    pan = Column(String(19))                        # 卡号
    trans_amt = Column(String(12))                  # 交易金额
    trans_date = Column(String(8))                  # 交易日期
    trans_time = Column(String(6))                  # 交易时间
    merno = Column(String(15))                      # 商户号
    terminal = Column(String(8))                    # 终端号
    resp_code = Column(String(5))                   # 响应码
    bank_date = Column(String(8))                   # 清算日期
    org_trans_sn = Column(String(30))              # 原交易流水号（退货用）
    org_rrn = Column(String(12))                   # 原交易参考号（退货用）
    pay_order = Column(String(20))                 # 外部订单号
    created_at = Column(DateTime, default=func.now())

    class Config:
        orm_mode = True
        from_attributes = True

    def to_dict(self):
        return {
            "id": self.id,
            "trans_code": self.trans_code,
            "trans_sn": self.trans_sn,
            "rrn": self.rrn,
            "orderid": self.orderid,
            "pan": self.pan,
            "trans_amt": self.trans_amt,
            "trans_date": self.trans_date,
            "trans_time": self.trans_time,
            "merno": self.merno,
            "terminal": self.terminal,
            "resp_code": self.resp_code,
            "bank_date": self.bank_date,
            "org_trans_sn": self.org_trans_sn,
            "org_rrn": self.org_rrn,
            "pay_order": self.pay_order,
            "created_at": self.created_at.isoformat() if self.created_at else None
        } 